import axios from 'axios'
import router from '@/router'
import { useAuthStore } from '@/stores/user'

//
// 创建axios实例
var instance = axios.create({
  timeout: 1000 * 60,
  baseURL: '/api',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})

const login = () => {
  let store = useAuthStore()
  store.setAuth(false)
  store.setRedirect(router.currentRoute.value.name)
  router.replace({
    path: '/login'
  })
}

const errorHandle = (err, msg) => {
  msg = msg == undefined ? '请求异常' : msg
  switch (err) {
    // 401: 未登录状态，跳转登录页
    case 401:
      ElMessage({ type: 'warning', message: '请先登录' })
      login()
      break
    case 403:
      ElMessage({ type: 'warning', message: msg })
      // setTimeout(() => {
      //   login()
      // }, 1000)
      break
    case 404:
      ElMessage({ type: 'warning', message: msg })
      break
    default:
      ElMessage({ type: 'warning', message: msg })
  }
}
//请求拦截器
instance.interceptors.request.use((req) => {
  let store = useAuthStore()
  if (store.user.isAuthenticated) req.headers['Authorization'] = store.user.token
  else login()
  return req
})
// 响应拦截器
instance.interceptors.response.use(
  //http请求200
  (res) => {
    switch (res.data.code) {
      case 200:
        if (res.data.t != undefined) {
          res.data.data['t'] = res.data.t
        }
        return Promise.resolve(res.data.data)
      case 400:
        ElMessage({ message: res.data.message, type: 'warning' })
        return Promise.reject(res.data)
      case 401:
        return login()
      case 403:
        ElMessage.warn('无权限访问')
        return Promise.reject(res)
      case 500:
        ElMessage.error(res.data.message == undefined ? '未知错误' : res.data.message)
        return Promise.reject(res)
      default:
        break
    }
  },
  // 请求失败
  (error) => {
    const { response } = error
    if (response) {
      // 请求已发出，但是不在2xx的范围
      errorHandle(response.status, response.data.message)
      return Promise.reject(response)
    } else {
      // 处理断网的情况
      ElMessage.error('网络异常')
      return Promise.reject(error)
    }
  }
)
export default instance
